package tools.project.controller {
	import kiwi.action.base.DelayAction;

	import flash.filesystem.File;

	import kiwi.action.base.DispatchEventAction;
	import kiwi.action.base.FunctionAction;
	import kiwi.action.base.WaitEventAction;
	import kiwi.action.queue.Queue;
	import kiwi.debug.Log;
	import kiwi.event.ActionEvent;

	import org.aswing.JOptionPane;
	import org.robotlegs.mvcs.Command;

	import tools.event.ProjectEvent;
	import tools.utils.NoFaultQueue;

	/**
	 * @author zhangming.luo
	 */
	public class BatchPublishCommand extends Command {
		private var dir : File;
		private var path : String;
		private var quality : int;

		override public function execute() : void {
			JOptionPane.showInputDialog("选择目录", "选择导出的目录", function(p : String) : void {
				path = p;
				JOptionPane.showInputDialog("发布", "发布的品质(默认80%)", function(q : String) : void {
					quality = int(q.replace("%", ""));
					handleSelected();
				}, "80%");
			},"e:\\Desktop\\mengjiang", null, true);
		}

		private function handleSelected() : void {
			dir = File.applicationDirectory.resolvePath(path);
			var global : Queue = new Queue();
			for each (var file:File in dir.getDirectoryListing()) {
				if (!file.isDirectory) {
					continue;
				}
				var spriteFile : File = file.resolvePath(file.name.replace(/^[^_]+_(.+)/, "$1") + ".sprite");
				var textureFile : File = file.resolvePath(file.name.replace(/^[^_]+_(.+)/, "$1") + ".png");
				textureFile == null?textureFile = file.resolvePath("texture.png"):null;
				if (!spriteFile.exists || !textureFile.exists) {
					Log.debug("系统", "文件不完整 " + file.name);
					continue;
				}
				var queue : Queue = new NoFaultQueue();
				queue.submit(new FunctionAction(Log.info, "发布文件 " + file.name));
				queue.submit(new DispatchEventAction(eventDispatcher, new ProjectEvent(ProjectEvent.LOAD, false, false, spriteFile)));
				queue.submit(new WaitEventAction(eventDispatcher, ProjectEvent.LOAD_COMPLETE));
				queue.submit(new DelayAction(1000));
				queue.submit(new DispatchEventAction(eventDispatcher, new ProjectEvent(ProjectEvent.PUBLISH, false, false, null, true, quality)));
				queue.submit(new WaitEventAction(eventDispatcher, ProjectEvent.PUBLISH_COMPLETE));
				queue.submit(new FunctionAction(Log.info, "发布文件完毕 " + file.name));
				global.submit(queue);
			}
			global.addEventListener(ActionEvent.ACTION_COMPLETE, handleComplete);
			global.addEventListener(ActionEvent.ACTION_FAULT, handleError);
			global.execute();
		}

		private function handleComplete(event : ActionEvent) : void {
			Log.alert("批量发布完毕");
		}

		private function handleError(event : ActionEvent) : void {
			Log.alert("批量发布失败");
		}
	}
}
